
//
//  WCBCaptureDataViewController.m
//  WeChatBuniess
//
//  Created by Guo Rui on 2017/12/19.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "WCBCaptureDataViewController.h"
#import "UIImage+Ex.h"
#import "YYModel.h"
#import "WCAWeChatTimelineModel.h"
#import "WCASessionManager.h"
#import "WCAHTTPRequestSerializer.h"
#import "TFToast.h"
#import "TFWeakTimer.h"
#import "WCBDataHelper.h"
#import "WCBPostMessageViewController.h"


@interface WCBCaptureDataViewController ()

@property (strong, nonatomic) UIImageView *loadingImageView;
@property (strong, nonatomic) UILabel *captureDescLabel;
@property (strong, nonatomic) UIButton *retryButton;
@property (strong, nonatomic) TFWeakTimer *timer;
@property (strong, nonatomic) NSString *bookId;
/**
 向服务器上传朋友圈数据

 @param datas 朋友圈的数据
 */
- (void)uploadCaptureData:(NSArray *)datas;

/**
 轮询判断书是否制作成功
 */
- (void)pollingForBookCreateSuccess;
@end

@implementation WCBCaptureDataViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupViews];
    

    NSString *path = [[NSBundle mainBundle] pathForResource:@"test.plist" ofType:nil];
    NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
    NSArray *array = [WCAWeChatTimelineModel modelWithArray:dictArray];
    
    // 开始对数据按照年月分组。
    [WCBDataHelper.sharedHelper beginAnalyse:array];
    
    [self uploadCaptureData:array];
    
    
    
}

- (void)setupViews
{
    CGFloat x, y, w, h;
    CGFloat width = CGRectGetWidth(self.view.frame);
    CGFloat height = CGRectGetHeight(self.view.frame);
    
    {
        w = h = 200;
        y = height - 600;
        x = (width - w) / 2.f;
        self.loadingImageView.frame = CGRectMake(x, y, w, h);
        
    }
    
    {
        x = 30;
        y = CGRectGetMaxY(self.loadingImageView.frame) + 30.f;
        w = width - 2 * x;
        h = 40.f;
        self.captureDescLabel.frame = CGRectMake(x, y, w, h);
    }
    
    {
        x = 120;
        y = CGRectGetMaxY(self.captureDescLabel.frame) + 20.f;
        w = width - 2 * x;
        h = 60.f;
        self.retryButton.frame = CGRectMake(x, y, w, h);
        self.retryButton.enabled = NO;
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

#pragma mark - Private
- (void)uploadCaptureData:(NSArray *)datas
{
    NSString *userId = [WCBDataHelper.sharedHelper getCurrentUserModel].userId;
    NSDictionary *dict = @{ @"data" : [datas yy_modelToJSONObject],
                            @"userId" : userId,
                            @"wechatAvatar" : @"",
                            @"wechatId" : @"xytgr12",
                            @"wechatUserName" : @"郭睿"
                            };
    
//    NSString *jsonString = [dict yy_modelToJSONString];
    
//    NSLog(@"%@", jsonString);
    __weak WCBCaptureDataViewController * weakself = self;
    WCAJSONRequestSerializer *serializer = [WCAJSONRequestSerializer serializer];
    [WCASessionManager setRequestSerialization:serializer];
    [WCASessionManager POST:@"weimport/mtime/addTimeToUser" parameters:dict success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *code = responseObject[@"code"];
        NSString *bookId = responseObject[@"bookId"];
        
        NSString *message = nil;
        NSString *messageForUser = nil;
        BOOL success = NO;
        if ([code isEqualToString:@"000"]) {
            message = @"发送成功";
            messageForUser = @"发送成功";
            success = YES;
        }
        else if ([code isEqualToString:@"TM001001"]) {
            message = @"请求参数不正确";
            messageForUser = @"发送失败，请重试";
        }
        else if ([code isEqualToString:@"TM001002"]) {
            message = @"数据异常";
            messageForUser = @"发送失败，请重试";
        }
        else if ([code isEqualToString:@"TM001003"]) {
            message = @"时光ID不存在";
            messageForUser = @"发送失败，请重试";
        }
        else if ([code isEqualToString:@"TM001004"]) {
            message = @"用户没有发起微信数据导入";
            messageForUser = @"发送失败，请重试";
        }
        
        if (message) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [TFToast toast:message];
                if (success) {
                    weakself.retryButton.enabled = NO;
                    [weakself.retryButton setTitle:messageForUser forState:UIControlStateDisabled];
                    weakself.captureDescLabel.text = @"正在制作，请稍等...";
                    weakself.bookId = bookId;
                    [weakself pollingForBookCreateSuccess];
                }
                else {
                    weakself.retryButton.enabled = NO;
                    [weakself.retryButton setTitle:messageForUser forState:UIControlStateNormal];
                    weakself.captureDescLabel.text = @"数据出错，请退出重试";
                }
            });
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *messageForUser = @"您的网络不给力，请重试";
                [TFToast toast:messageForUser];
                weakself.retryButton.enabled = YES;
                [weakself.retryButton setTitle:messageForUser forState:UIControlStateNormal];
            });
    }];
}

- (void)pollingForBookCreateSuccess
{
    self.timer = [TFWeakTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(requestForQueryBookCreateSuccess) userInfo:nil repeats:YES dispatchQueue:dispatch_get_main_queue()];
}

- (void)requestForQueryBookCreateSuccess
{
    __weak WCBCaptureDataViewController * weakself = self;
    WCAHTTPRequestSerializer *serializer = [WCAHTTPRequestSerializer serializer];
    [WCASessionManager setRequestSerialization:serializer];
   
    NSString *userId = WCBDataHelper.sharedHelper.getCurrentUserModel.userId;
    [WCASessionManager POST:@"weimport/mtime/getWeChatBookInfo" parameters:@{ @"bookId": self.bookId, @"userId": userId } success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSDictionary *result = [responseObject objectForKey:@"bookObj"] ? [responseObject objectForKey:@"bookObj"] : @{ @"created" : @(NO) };
        if ([[result objectForKey:@"created"] boolValue] && [[result objectForKey:@"pageSize"] integerValue]) {
            // 书已做完
            [weakself.timer invalidate];
            weakself.timer = nil;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [TFToast toast:@"恭喜您，已制作完成"];
                weakself.captureDescLabel.text = @"已制作完成";
                
                WCBWeChatBookModel *bookModel = [WCBWeChatBookModel modelWithDict:result];
                WCBPostMessageViewController *vc = [[WCBPostMessageViewController alloc] init];
                vc.bookModel = bookModel;
                [weakself.navigationController pushViewController:vc animated:YES];
            });
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"获取书接口错误 - %@", error.localizedDescription);
    }];
}

- (void)setAnimationImages:(UIImageView *)imageView
{
    NSMutableArray *animationImages = [NSMutableArray arrayWithCapacity:0];
    for (int i = 1; i < 8; i++) {
        [animationImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"state_loading_%zd.png", i]]];
    }
    
    imageView.animationImages = animationImages;
    imageView.animationDuration = 0.3f;
    [imageView startAnimating];
}

- (void)setFailImage:(UIImageView *)imageView
{
    [_loadingImageView stopAnimating];
    _loadingImageView.image = [UIImage imageNamed:@"ViewDataNetError"];
}

#pragma mark - Actions
- (void)retryDidClick
{
    
}

#pragma mark - Getter
- (UIImageView *)loadingImageView
{
    if (!_loadingImageView) {
        _loadingImageView = [[UIImageView alloc] init];
        _loadingImageView.contentMode = UIViewContentModeScaleAspectFill;
        [self setAnimationImages:_loadingImageView];
        [self.view addSubview:_loadingImageView];
    }
    return _loadingImageView;
}

- (UILabel *)captureDescLabel
{
    if (!_captureDescLabel) {
        _captureDescLabel = [[UILabel alloc] init];
        _captureDescLabel.textColor = [UIColor colorWithRed:0.60 green:0.60 blue:0.60 alpha:1.00];
        _captureDescLabel.text = @"准备中...";
        _captureDescLabel.font = [UIFont systemFontOfSize:28];
        _captureDescLabel.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:_captureDescLabel];
    }
    return _captureDescLabel;
}


- (UIButton *)retryButton
{
    if (!_retryButton) {
        _retryButton = [UIButton buttonWithType:UIButtonTypeCustom];

        [_retryButton setTitle:@"等待发送..." forState:UIControlStateDisabled];
        [_retryButton setTitle:@"等待发送..." forState:UIControlStateNormal];
        
        [_retryButton setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
        [_retryButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _retryButton.titleLabel.font = [UIFont systemFontOfSize:28];
        
        [_retryButton setBackgroundImage:[UIImage tf_imageWithColor:[UIColor lightGrayColor]] forState:UIControlStateDisabled];
        [_retryButton setBackgroundImage:[UIImage tf_imageWithColor:[UIColor colorWithRed:0.11 green:0.62 blue:0.94 alpha:1.00]] forState:UIControlStateNormal];
        
        [_retryButton addTarget:self action:@selector(retryDidClick) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addSubview:_retryButton];
    }
    return _retryButton;
}

- (void)dealloc {
    NSLog(@"\n************\n %@ dealloc \n************", self.class);
}

@end
